import { useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import * as Tooltip from "@radix-ui/react-tooltip";

interface EncryptedPassword {
  id: number;
  title: string;
  username?: string;
  encrypted_password: string;
  website?: string;
  notes?: string;
  created_at?: string;
  updated_at?: string;
}

interface DecryptedPassword {
  title: string;
  username?: string;
  password: string;
  website?: string;
  notes?: string;
}

interface PasswordItemProps {
  password: EncryptedPassword;
  onEdit: (password: EncryptedPassword) => void;
  onDelete: (id: number) => void;
  onToast: (message: string, type: "success" | "error" | "info") => void;
}

export function PasswordItem({ password, onEdit, onDelete, onToast }: PasswordItemProps) {
  const [showPassword, setShowPassword] = useState(false);
  const [decryptedPassword, setDecryptedPassword] = useState<string | null>(null);
  const [decrypting, setDecrypting] = useState(false);
  const [expanded, setExpanded] = useState(false);

  const handleTogglePassword = async () => {
    if (showPassword) {
      setShowPassword(false);
      setDecryptedPassword(null);
      return;
    }

    try {
      setDecrypting(true);
      
      const decrypted = await invoke<DecryptedPassword>("decrypt_password_data", {
        encryptedData: password,
      });

      setDecryptedPassword(decrypted.password);
      setShowPassword(true);
    } catch (error) {
      console.error("Failed to decrypt password:", error);
      onToast(`解密失败: ${error}`, "error");
    } finally {
      setDecrypting(false);
    }
  };

  const handleCopyPassword = async () => {
    try {
      if (!decryptedPassword) {
        const decrypted = await invoke<DecryptedPassword>("decrypt_password_data", {
          encryptedData: password,
        });

        await writeText(decrypted.password);
      } else {
        await writeText(decryptedPassword);
      }

      onToast("密码已复制到剪贴板", "success");
    } catch (error) {
      console.error("Failed to copy password:", error);
      onToast(`复制失败: ${error}`, "error");
    }
  };

  const handleCopyUsername = async () => {
    if (!password.username) return;

    try {
      await writeText(password.username);
      onToast("用户名已复制到剪贴板", "success");
    } catch (error) {
      console.error("Failed to copy username:", error);
      onToast(`复制失败: ${error}`, "error");
    }
  };

  const formatDate = (dateString?: string) => {
    if (!dateString) return "";
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getFavicon = (website?: string) => {
    if (!website) return null;
    try {
      // Try to parse as URL
      let url;
      // If doesn't start with protocol, try adding https://
      if (!/^https?:\/\//i.test(website)) {
        url = new URL(`https://${website}`);
      } else {
        url = new URL(website);
      }
      // Only return favicon if it has a valid hostname
      if (url.hostname && url.hostname !== 'localhost' && !url.hostname.startsWith('127.')) {
        return `https://www.google.com/s2/favicons?domain=${url.hostname}&sz=32`;
      }
      return null;
    } catch {
      // If URL parsing fails, it's not a valid URL, return null to show default icon
      return null;
    }
  };

  const favicon = getFavicon(password.website);

  return (
    <div className="border-b border-border hover:bg-muted/50 transition-colors">
      {/* Main Row */}
      <div className="flex items-center gap-3 px-4 py-3">
        {/* Website */}
        <div className="flex items-center gap-2 flex-1 min-w-[180px]">
          {favicon ? (
            <img src={favicon} alt="" className="w-6 h-6 rounded flex-shrink-0" />
          ) : (
            <div className="w-6 h-6 bg-primary/10 rounded flex items-center justify-center flex-shrink-0">
              <svg className="w-3 h-3 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
            </div>
          )}
          <div className="flex-1 min-w-0">
            <div className="font-medium text-foreground truncate">{password.title}</div>
            <div className="text-xs text-muted-foreground truncate">
              {password.website ? password.website.replace(/^https?:\/\//i, '') : '-'}
            </div>
          </div>
        </div>

        {/* Username/Account */}
        <div className="w-[160px] text-sm text-foreground truncate">
          {password.username || '-'}
        </div>

        {/* Password Field */}
        <div className="flex items-center gap-2 w-[140px]">
          <span className="text-sm text-foreground font-mono">
            {decrypting ? (
              <span className="text-muted-foreground">解密中...</span>
            ) : showPassword && decryptedPassword ? (
              decryptedPassword.substring(0, 12) + (decryptedPassword.length > 12 ? '...' : '')
            ) : (
              "••••••••••••"
            )}
          </span>
        </div>

        {/* Notes */}
        <div className="hidden lg:block flex-1 min-w-[120px]">
          {password.notes ? (
            <Tooltip.Provider delayDuration={300}>
              <Tooltip.Root>
                <Tooltip.Trigger asChild>
                  <div className="text-sm text-muted-foreground truncate cursor-default">
                    {password.notes}
                  </div>
                </Tooltip.Trigger>
                <Tooltip.Portal>
                  <Tooltip.Content
                    className="max-w-[400px] px-3 py-2 bg-popover text-popover-foreground text-sm rounded-md shadow-md z-50 break-words"
                    sideOffset={5}
                  >
                    {password.notes}
                    <Tooltip.Arrow className="fill-popover" />
                  </Tooltip.Content>
                </Tooltip.Portal>
              </Tooltip.Root>
            </Tooltip.Provider>
          ) : (
            <div className="text-sm text-muted-foreground">-</div>
          )}
        </div>

        {/* Action Buttons */}
        <div className="flex items-center gap-1 flex-shrink-0">
          <button
            onClick={handleCopyUsername}
            className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors"
            title="复制用户名"
            disabled={!password.username}
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
          </button>
          <button
            onClick={handleCopyPassword}
            className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors"
            title="复制密码"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
          </button>
          <button
            onClick={handleTogglePassword}
            disabled={decrypting}
            className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors disabled:opacity-50"
            title={showPassword ? "隐藏密码" : "显示密码"}
          >
            {showPassword ? (
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
              </svg>
            ) : (
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
            )}
          </button>
          <button
            onClick={() => onEdit(password)}
            className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors"
            title="编辑"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
          </button>
          <button
            onClick={() => onDelete(password.id)}
            className="p-1.5 text-muted-foreground hover:text-red-500 hover:bg-muted rounded transition-colors"
            title="删除"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          </button>
          <button
            onClick={() => setExpanded(!expanded)}
            className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors"
            title={expanded ? "收起" : "展开"}
          >
            <svg
              className={`w-4 h-4 transition-transform ${expanded ? "rotate-180" : ""}`}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
        </div>
      </div>

      {/* Expanded Details */}
      {expanded && (
        <div className="px-4 pb-3 bg-muted/30">
          <div className="flex gap-6 pt-3">
            {/* Left Column */}
            <div className="flex-1 space-y-2">
              {password.website && (
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1 block">网站</label>
                  <a
                    href={password.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-sm text-primary hover:underline break-all"
                  >
                    {password.website}
                  </a>
                </div>
              )}
              
              {password.notes && (
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1 block">备注</label>
                  <p className="text-sm text-foreground whitespace-pre-wrap">
                    {password.notes}
                  </p>
                </div>
              )}
            </div>

            {/* Right Column */}
            <div className="w-64 space-y-2">
              {password.created_at && (
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1 block">创建时间</label>
                  <div className="text-sm text-foreground">{formatDate(password.created_at)}</div>
                </div>
              )}
              {password.updated_at && (
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1 block">更新时间</label>
                  <div className="text-sm text-foreground">{formatDate(password.updated_at)}</div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
